package com.xbongbong.paas.toolbox.thread;

import java.util.HashMap;
import java.util.Map;

/**
 * 本地线程变量 通用帮助类
 *  记得remove
 * @author zheng.li
 **/
public class ThreadLocalUtil {

    private static ThreadLocal<Map<String,Object>> threadLocalMap = null;

    public static void setValue (String key,Object value) {
        if (threadLocalMap == null) {
            threadLocalMap = new ThreadLocal<>();
        }
        Map<String,Object> map = threadLocalMap.get();
        if (map == null) {
            map = new HashMap<>(16);
        }
        map.put(key,value);
        threadLocalMap.set(map);
    }


    public static String getStringValue(String key) {
        Object obj = getValue(key);
        return (String) obj;
     }

    public static Object getValue(String key) {
        if (threadLocalMap == null) {
            return null;
        }
        Map<String,Object> map = threadLocalMap.get();
        if (map == null) {
            return null;
        }
        return map.get(key);
    }

    public static void remove() {
        if (threadLocalMap != null) {
            threadLocalMap.remove();
        }
    }


}
